/**
 * 获取所有的章节页
 */
const bookModel = require('../model/bookModel');
const chapterModel = require('../model/chapterModel');
const { website } = require('../config');
const book = require('../model/book');
const superagent = require('superagent');
const cheerio = require('cheerio');
const logger = require('../config/log4');
const { getBookDetail } = require('../controls/detail');
const request = require('request');
const fs = require('fs');
/**
 * 获取章节
 */
const getChapter = async (data)=>{
    getBookDetail();
    return;
    if(!data){
        data = await bookModel.getFirstAndRemove();
    }
    if(data){
        //根据id获取页面信息
        superagent
            .get(`${website.baseurl}${data.url}`)
            .end(async (err,res)=>{
                if(err){
                    setTimeout(() => {
                        getChapter(data);
                    }, 100000);
                    throw err;
                }
                const $ = cheerio.load(res.text);
                const chapters = [];
                $("dd a").each((index, item) => {
                    if($(item).attr('href').indexOf('book') >= 0){
                        //是章节信息
                        chapters.push({
                            chapterName: $(item).text(),
                            url: $(item).attr('href'),
                            bookId : data.id
                        })
                    }
                })
                const params = {
                    name: $('h1').text(),
                    author: $($('#info p')[0]).text().split('：')[1],
                    time: $($('#info p')[2]).text().split('：')[1],
                    type: data.type,
                    img: savePic($("#fmimg img").attr('src')),
                    id: data.id
                }
                var saveChapter = await chapterModel.saveChapters(chapters);
                var saveRes = await book.saveOneBook(params)
                if(saveChapter.length > 0 ){
                    logger.info(`保存${params.name}成功`)
                    getChapter();
                }
            })
    }else {
        logger.info('全部章节保存成功');
        getBookDetail()
    } 
}
/**
 * 保存图片并返回地址
 */
const savePic = (url) => {
    const name = url.split('/')[3];
    const imgUrl = `./upload/${name}`;
    var res = request(`${website.baseurl}${url}`).pipe(fs.createWriteStream(imgUrl))
    if(res){
        return imgUrl;
    }else {
        return false;
    }
}
module.exports = {
    getChapter
}